﻿using MDK.Common;
using MDK.Device;
using MDK.Model.Models;
using MDK.WebApi;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
/// <summary>
/// 登录
/// </summary>

namespace MDK.Winform
{
    public partial class frmLogin : BaseForm
    {
        private UInt32 N_ADDR = 0XFFFFFFFF;//设备地址
        private Bitmap bmp = new Bitmap(256, 288);//指纹图片
        private IntPtr DeviceHandle = IntPtr.Zero;
        private Thread CollectionThread = null;

        private bool IsCollection = false;

        private List<int?> AllFingerIDs { get; set; }
        /// <summary>
        /// 默认无参构造函数
        /// </summary>
        public frmLogin()
        {
            InitializeComponent();

        }

        public List<int?> GetAllFingerID()
        {
            string url = string.Format("User/FindList?jsonWhere={0}&orderPropertyName={1}&isAsc=false", "", "");
            return WebAPIHelper.Get<List<T_User>>(url).Select(t => t.FingerID).ToList();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void frmLogin_Load(object sender, EventArgs e)
        {
            //AllFingerIDs = GetAllFingerID();
            var LoginType = System.Configuration.ConfigurationSettings.AppSettings["PcType"].ToString();
            if (LoginType == "ATM")
            {
                radioLoginType.Visible = true;
            }
        }

        /// <summary>
        /// 登录按钮点击事件
        /// </summary>
        private void btnLogin_Click(object sender, EventArgs e)
        {try
            {
                string account = txtAccount.Text.Trim();
                string password = txtPW.Text.Trim();
                if (account == null && password == null)
                {
                    //提示输入有误
                    new frmFastMessageBox("提示", "输入有误，请重新输入", frmFastMessageBox.MessageBoxStyle.error).ShowDialog();
                }
                else
                {
                    string psw = DESEncrypt.Encrypt(password);
                    PropertyHelper jsonWhere = new PropertyHelper();
                    if (radioLoginType.SelectedIndex == 1)
                    {
                        jsonWhere.Addproperty(CompareType.Equal, "IDCard", account);
                    }
                    else
                    {
                        jsonWhere.Addproperty(CompareType.Equal, "LoginName", account);
                        jsonWhere.Addproperty(CompareType.Equal, "Password", psw);
                    }
                    jsonWhere.Addproperty(CompareType.Equal, "Is_Enable", true);
                    string url = string.Format("User/Find?jsonWhere={0}", JsonConvert.SerializeObject(jsonWhere.propertyList));
                    var user = WebAPIHelper.Get<T_User>(url);
                    if (user != null)
                    {
                        App.LoadUser(user);
                        DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        FastMessageBox.Question("请确认账号密码");
                    }
                }
            }
            catch(Exception ex) {
                FastMessageBox.Error("确认预处理是否开机");
            }
        }

        private void Login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(null, null);
            }
        }

        private void radioLoginType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioLoginType.SelectedIndex == 0)
            {
                txtAccount.Text = "";
                txtAccount.Focus();
                lb1.Visible = true;
                txtAccount.Visible = true;
                lb2.Visible = true;
                txtPW.Visible = true;
                btnLogin.Visible = true;
            }
            else
            {
                txtAccount.Text = "";
                txtPW.Text = "";
                txtAccount.Focus();
                lb1.Visible = false;
                txtAccount.Visible = false;
                lb2.Visible = false;
                txtPW.Visible = false;
                btnLogin.Visible = false;
            }
        }


        #region 指纹识别

        public void OpenDevice()
        {
            try
            {
                int devce_usb = 0;
                byte[] iPwd = new byte[4];
                int result = DriveOperation.ZAZOpenDeviceEx(ref DeviceHandle, 2, 0, 0, 2, 0);
                if (result == 0)
                {
                    devce_usb = 2;  //无驱
                }
                if (devce_usb == 1)
                {
                    if (DriveOperation.ZAZVfyPwd(DeviceHandle, N_ADDR, iPwd) != 0)
                    {
                        SendMessage(string.Format("打开设备失败:打开指纹采集模块失败,错误码：{0}", result));
                    }
                }
                else if (devce_usb == 2)
                {
                    SendMessage("打开指纹采集模块成功");
                    CollectionThread = new Thread(new ThreadStart(Search));
                    CollectionThread.Start();
                }
            }
            catch (Exception ex)
            {
                SendMessage(string.Format("打开设备失败:{0}", ex.Message));
                StopSearch();
            }
            finally
            {

            }
        }

        private void StopSearch()
        {
            IsCollection = true;
            DriveOperation.ZAZCloseDeviceEx(DeviceHandle);
            SendMessage("停止采集...");
        }

        private void SendMessage(string str)
        {
            lbMessage.Invoke(new MethodInvoker(() =>
            {
                if (lbMessage.IsHandleCreated)
                {
                    lbMessage.Text = str;
                }
            }));
        }

        private void Search()
        {
            while (!IsCollection)
            {
                try
                {
                    int ret = 0;
                    //3获取指纹图像  4.上传指纹图像(可省略) 5.显示指纹图像(可省略)  6.生成特征A  
                    if (UpImage(DeviceHandle, N_ADDR, 1) != 1)
                    {
                        continue;
                    }
                    Thread.Sleep(200);

                    //循环数据库FingerID
                    foreach (var FingerId in AllFingerIDs)
                    {
                        if (FingerId == null) continue;
                        ret = DriveOperation.ZAZLoadChar(DeviceHandle, N_ADDR, 2, FingerId.Value);
                        if (ret != 0)
                        {
                            ShowErrorMess(ret);
                            continue;
                        }
                        else
                        {
                            SendMessage("加载指纹成功");
                        }
                        Thread.Sleep(200);

                        //8进行1:1比对
                        int[] nScore = new int[1];
                        ret = DriveOperation.ZAZMatch(DeviceHandle, N_ADDR, nScore);  //比对模板
                        if (nScore[0] < 50)
                        {
                            SendMessage("比对得分:" + nScore[0].ToString());
                            Thread.Sleep(1000);
                            continue;
                        }
                        else
                        {
                            IsCollection = true;
                            PropertyHelper jsonWhere = new PropertyHelper();
                            jsonWhere.Addproperty(CompareType.Equal, "FingerID", true);
                            jsonWhere.Addproperty(CompareType.Equal, "Is_Enable", true);
                            string url = string.Format("User/Find?jsonWhere={0}", JsonConvert.SerializeObject(jsonWhere.propertyList));
                            var user = WebAPIHelper.Get<T_User>(url);
                            if (user != null)
                            {
                                App.LoadUser(user);
                                DialogResult = DialogResult.OK;
                            }
                        }
                    }
                }
                catch
                {
                    
                }
            }
        }

        private int UpImage(IntPtr hHandle, UInt32 nDevAddr, int buffer)
        {
            try
            {
                int ret = 0;
                byte[] ImgData = new byte[1024];
                int[] ImgLen = new int[1];
                int iBuffer = buffer;
                /****************获取图像*********/
                do
                {
                    SendMessage("请将手指平放在传感器上...");
                    ret = DriveOperation.ZAZGetImage(hHandle, nDevAddr);  //获取图象 
                }
                while (ret != DriveOperation.PS_OK);

                SendMessage("获取图像成功...");
                /****************生成特征 *********/
                ret = DriveOperation.ZAZGenChar(hHandle, nDevAddr, iBuffer);  //生成模板
                if (ret != 0)
                {
                    ShowErrorMess(ret);
                    return 0;
                }
                else
                {
                    SendMessage("生成指纹特征...");
                    return 1;
                }
            }
            catch
            {
                return 0;
            }
        }

        private void ShowErrorMess(int errorCode)
        {
            string sb = DriveOperation.ZAZErr2Str(errorCode);
            SendMessage(string.Format("录入指纹失败：{0}", sb));
        }

        /// <summary>
        /// 显示指纹图片
        /// </summary>
        /// <param name="rgbValues"></param>
        public void ShowFingerPrint(byte[] rgbValues)
        {
            bmp = new Bitmap(256, 238);
            for (int i = 0; i < bmp.Height; i++)
            {
                for (int j = 0; j < bmp.Width; j++)
                {
                    int value = (int)rgbValues[i * bmp.Width + j];
                    Color c = Color.FromArgb(value, value, value);

                    bmp.SetPixel(j, i, c);
                }
            }
            bmp.Save(string.Format(@"{0}\printer.bmp", Application.StartupPath));
            //this.pic.BackgroundImage = bmp;
            //this.pic.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
        }

        #endregion
    }
}
